package com.gnkexy.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.gnkexy.springframework.beans.BeansException;
import com.gnkexy.springframework.beans.PropertyValue;
import com.gnkexy.springframework.beans.PropertyValues;
import com.gnkexy.springframework.beans.factory.*;
import com.gnkexy.springframework.beans.factory.config.AutowireCapableBeanFactory;
import com.gnkexy.springframework.beans.factory.config.BeanDefinition;
import com.gnkexy.springframework.beans.factory.config.BeanPostProcessor;
import com.gnkexy.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] agrs) throws BeansException {
        Object bean = null;
        try {
            //Bean的实例化
            bean = createBeanInstance(beanDefinition, beanName, agrs);
            //填充属性
            applyPropertyValues(beanName, bean, beanDefinition);
            //执行Bean的初始化方法和BeanPostProsecc的前置和后置方法
            bean = initializeBean(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        //将销毁方法放进DefaultSingletonBeanRegistry中的
        // Map<String, DisposableBean> disposableBeans属性中去
        registerDisposableBeanIfNecessary(beanName, bean, beanDefinition);

        //判断 SCOPE_SINGLETON、SCOPE_PROTOTYPE ，非单例不存入单例池
        if (beanDefinition.isSingletin()) {
            addSingleton(beanName, bean);
        }
        return bean;
    }

    private void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        //非Singletin的bean不执行销毁方法
        if (!beanDefinition.isSingletin()) return;
        //如果这个bean有实现了DisposableBean接口的销毁方法或者有自定义的销毁方法，就把
        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition.getDestroyMethodName()));
        }
    }


    private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {

        //Aware容器感知 在bean初始化时给实现了Aware接口的bean设置感知对象
        if (bean instanceof Aware) {
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(this);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getClassLoader());
            }
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
        }

        //执行BeanPostProcess的after方法
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        try {
            invokeInitMethods(beanName, wrappedBean, beanDefinition);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //执行BeanPostProcess的before方法
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName);

        return wrappedBean;
    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object bean, String beanName) {
        Object result = bean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(bean, beanName);
            if (null != current) return result;
            result = current;
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object bean, String beanName) {
        Object result = bean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(bean, beanName);
            if (null != current) return result;
            result = current;
        }
        return result;
    }

    private void invokeInitMethods(String beanName, Object wrappedBean, BeanDefinition beanDefinition) {
        //执行实现initializingBean接口的初始化方法
        if (wrappedBean instanceof InitializingBean) {
            ((InitializingBean) wrappedBean).afterPropertiesSet();
        }
        //执行自定义的的初始化方法
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName)) {
            try {
                Method method = beanDefinition.getBeanClass().getMethod(initMethodName);
                if (method != null) {
                    method.invoke(wrappedBean);
                }
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    }


    //bean实例化
    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
    }

    //bean属性注入
    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            PropertyValue[] properS = propertyValues.getProperS();

            for (PropertyValue proper : properS) {
                String name = proper.getName();
                Object value = proper.getValue();

                if (value instanceof BeanReference) {
                    BeanReference beand = (BeanReference) value;
//                    value = getBean(beand.getBeanName());
                    value = doGetBean(beand.getBeanName(),new Object[0]);
                }
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

}
